const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
const db = cloud.database()
const _ = db.command
const $ = db.command.aggregate

exports.main = async (event, context) => {
  const doc = event.data.doc;
  let remark = '';
  if (event.data.dataType == 'insert') {
    remark = '创建订单'
  } else if (event.data.dataType == 'update') {
    const couponStatus = (await db.collection('tb_coupon').where({ order_id: doc._id }).get()).data.map(o => o.coupon_state);
    switch (doc.order_state) {
      case 1:
        if (couponStatus.length) {
          remark = '预约已过期或已退款';
        } else {
          remark = '超时未支付';
        }
        break;
      case 2:
        remark = '已支付';
        break;
      case 3:
        remark = '全部预约已核销';
        break;
    }
  }
  await db.collection('tb_order_change').add({
    data: {
      modified_state: doc.order_state,
      modified_time: new Date().getTime(),
      order_id: doc._id,
      operator_id: doc.modified_user_id,
      remark: remark,
    }
  })
}